﻿using Model.Entities_EF;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.Extensions.Logging;
using Model;

namespace OperationDataBase
{
    public class Data_Storage
    {
        private readonly int queuecount = 100;
        private readonly ILogger<Data_Storage> _logger;
        private readonly RSServerSettingsModel _rsServerSettingsModel;
        ConcurrentQueue<Tbhistory> _tbhistoryQueue = new ConcurrentQueue<Tbhistory>();
        public Data_Storage(
            ILogger<Data_Storage> logger,
            RSServerSettingsModel rsServerSettingsModel
            )
        {
            _logger = logger;
            _rsServerSettingsModel = rsServerSettingsModel;
        }
        public string TbhistoryToQueue(Tbhistory tbhistory)
        {
            lock (_tbhistoryQueue)
            {
                if (_tbhistoryQueue.Count < queuecount)
                {
                    _tbhistoryQueue.Enqueue(tbhistory);
                    return null;
                }
                return Data_Install(_tbhistoryQueue);
            }

        }
        /// <summary>
        /// 数据入库
        /// </summary>
        /// <param name="tbhistory"></param>
        /// <returns></returns>
        public string Data_Install(ConcurrentQueue<Tbhistory> _tbhistoryQueue)
        {

            try
            {
                string str = $"数据入库 方法收到{_tbhistoryQueue.Count} 条 \r\n";
                List<Tbhistory> listHistory = new List<Tbhistory>();
                lock (listHistory)
                {
                    while (_tbhistoryQueue.Count > 0)
                    {
                        _tbhistoryQueue.TryDequeue(out Tbhistory dequeueTbhistory);
                        listHistory.Add(dequeueTbhistory);
                    }
                    str += $" List<Tbhistory> 中有{listHistory.Count} 条 \r\n";
                    var savecount = 0;
                    using (var _icPrkmonitorContext = new ICPrkmonitorContext(_rsServerSettingsModel))
                    {
                        _icPrkmonitorContext.Tbhistory.AddRange(listHistory);
                        savecount = _icPrkmonitorContext.SaveChanges();
                    }
                    return str += $"代码执行时间：{DateTime.Now} 入库时间:{DateTime.Now} 成功添加数据库:{ savecount} 条数据.";
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message);
                return null;
            }
        }
    }
}
